package com.example.Laboratory.Service.Impl;

import com.example.Laboratory.Entity.Resource_sharing;
import com.example.Laboratory.Mapper.Resource_sharingMapper;
import com.example.Laboratory.Service.Resource_sharingService;
import com.example.Laboratory.Untils.FileUtil;
import com.example.Laboratory.Untils.OperationFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;


@Service
public class Resource_sharingServiceImpl implements Resource_sharingService {

    @Autowired
    Resource_sharingMapper resource_sharingMapper;

    @Override
    public String addResource_sharing(MultipartFile file, String resource_sharing_time) {
        String fileName = file.getOriginalFilename();
        String path = OperationFile.upfile(file);
         if (path.equals("没有选择文件")) {
            return path;
        } else {
            Resource_sharing resource_sharing = new Resource_sharing();
            resource_sharing.setResource_sharing_address("E:/yyy/" + fileName);
            resource_sharing.setResource_sharing_name(fileName);
            resource_sharing.setResource_sharing_time(resource_sharing_time);
            resource_sharingMapper.addResource_sharing(resource_sharing);
            return "添加成功";
        }
    }


    @Override
    public String deleteResource_sharing(int resource_sharing_id) {
        //获取文件名称,包含后缀
        String resource_sharing_address = resource_sharingMapper.researchResource_sharing1(resource_sharing_id);
        int code = OperationFile.deletefile(resource_sharing_address);
        if (code == 1) {
            resource_sharingMapper.deleteResource_sharing(resource_sharing_id);
            return "删除成功";
        } else if (code == 0) {
            return "删除失败";
        } else if (code == 2) {
            return "文件不存在";
        } else {
            return "发生未知错误";
        }
    }

    @Override
    public List<Resource_sharing> researchResource_sharing() {
        return resource_sharingMapper.researchResource_sharing();
    }

    @Override
    public String reviseOrganization(MultipartFile file, Resource_sharing r) {
        int id = r.getResource_sharing_id();
        String fileName = file.getOriginalFilename();
        String filepath = resource_sharingMapper.researchResource_sharing1(id);
        String tip = OperationFile.updatafile(filepath, file);
        if (tip.equals("文件已存在")) {
            return tip;
        } else if (tip.equals("没有选择文件")) {
            return tip;
        } else if (tip.equals("更新失败")){
            return tip;
        } else {
            r.setResource_sharing_address(tip);
            r.setResource_sharing_name(fileName);
            resource_sharingMapper.reviseResource_sharing(r);
            return "修改成功";
        }
    }
}
